package com.bicon.botu.account.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.account.dto.AccountLogDTO;
import com.bicon.botu.account.entity.AccountLog;
import com.bicon.botu.account.mapper.AccountLogMapper;
import com.bicon.botu.account.service.IAccountLogService;
import com.bicon.botu.core.base.common.BusinessException;
import com.bicon.botu.core.base.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 张凡
 * @date 2018/1/4 14:30
 */
@Slf4j
@Service

public class AccountLogServiceImpl extends ServiceImpl<AccountLogMapper, AccountLog> implements IAccountLogService {
    @Autowired
    AccountLogMapper accountLogMapper;

    /**
     * 保存账户日志
     *
     * @param userId 用户id
     * @param type   类型：0-打开app时，1-唤醒时
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAccountLog(String userId, String type) {
        //判断此类型的记录是否存在
        AccountLog accountLog = new AccountLog().selectOne(new EntityWrapper<AccountLog>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("user_id", userId).eq("type", type));
        boolean result;
        //存在则修改
        if (accountLog != null) {
            accountLog.setUpdateDate(new Date());
            result = accountLog.updateById();
            if (!result) {
                throw new BusinessException(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
            }
        } else {
            //不存在则新增
            AccountLog accountLog1 = new AccountLog();
            accountLog1.setType(type);
            accountLog1.setUserId(userId);
            accountLog1.preInsert();
            result = accountLog1.insert();
            if (!result) {
                throw new BusinessException(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
            }
        }
    }

    /**
     * 查询多个账户日志
     *
     * @param list 多个账户的用户id
     * @param type 类型：0-打开app时，1-唤醒时
     * @return
     */
    @Override
    public List<AccountLogDTO> getAccountLogBatch(List<String> list, String type) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("list", list);
        map.put("type", type);
        return accountLogMapper.getAccountLogBatch(map);
    }
}
